package com.example.dangerouscargodriver.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.baiju.style.multipicker.HashMultiPickerView;
import com.baiju.style.multipicker.MultiPickerView;
import com.baiju.style.multipicker.config.MultiPickerConfig;
import com.baiju.style.multipicker.listener.OnHashMultiPickerItemClickListener;
import com.baiju.style.multipicker.listener.OnMultiPickerItemClickListener;
import com.baiju.style.multipicker.widget.bean.MultiItemBean;
import com.example.dangerouscargodriver.controller.AttrInfoController;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.EnterPlatformInfoController;
import com.example.dangerouscargodriver.controller.UserInfoController;
import com.example.dangerouscargodriver.entry.ResourceTypeInfo3;
import com.example.dangerouscargodriver.entry.TruckClassInfo;
import com.example.dangerouscargodriver.entry.TruckTypeInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.utils.DisplayUtil;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.google.gson.Gson;
import com.parkingwang.keyboard.OnInputChangedListener;
import com.parkingwang.keyboard.PopupKeyboard;
import com.parkingwang.keyboard.view.InputView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EnterPlatformPersonalStepTwoActivity extends HttpRequestActivity implements View.OnClickListener {

    private static final String TAG = "EnterPlatform";
    private ActionBar mActionBar = null;
    private Button mActionCommit = null;
    private LinearLayout mAddContactExtra = null;
    private LinearLayout mContactExtra = null;
    private EditText mHeft = null;
    private EditText mContactInfo = null;
    private EditText mTelephoneInfo = null;
    private EditText mContactInfoExtra = null;
    private EditText mTelephoneInfoExtra = null;

    //
    private LinearLayout mCarTypeSelector = null;
    private LinearLayout mCarType = null;

    //
    private HashMap<String, ArrayList<MultiItemBean>> mHashMapCarTypeArray = null;
    private ArrayList<String> mHashKeyArray = null;
    private HashMultiPickerView mCarTypePickerView = null;

    //
    private LinearLayout mResourceTypeSelector = null;
    private LinearLayout mResourceType = null;

    //
    private ArrayList<MultiItemBean> mResourceTypeArray = null;
    private MultiPickerView mResourceTypePickerView = null;

    //用户操作结果集
    private List<Integer> mSelectTruckCid = null;
    private String mSelectorTruck_cidKey = null;

    //
    private List<Integer> mSelectResource = null;

    //
    private HashMap<String, String> mSelectPicture = null;

    private InputView mInputView;
    private PopupKeyboard mPopupKeyboard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(EnterPlatformPersonalStepTwoActivity.class);
        AppManager.getAppManager().addActivity(this);

        setContentView(R.layout.activity_enter_platform_personal_step_two);
        mAddContactExtra = findViewById(R.id.ic_add_item);
        mAddContactExtra.setOnClickListener(this);
        mContactExtra = findViewById(R.id.layout_add_contact_extra);
        mHeft = findViewById(R.id.ed_heft);
        mContactInfo = findViewById(R.id.ed_contact_person);
        mTelephoneInfo = findViewById(R.id.ed_telephone_no);
        mContactInfoExtra = findViewById(R.id.ed_contact_person_extra);
        mTelephoneInfoExtra = findViewById(R.id.ed_telephone_no_extra);

        mActionCommit = findViewById(R.id.btn_action_commit);
        mActionCommit.setOnClickListener(this);

        mActionBar = findViewById(R.id.actionEnterPlatformPersonalStepTwo);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //
        mCarTypeSelector = findViewById(R.id.layout_car_type_select);
        mCarTypeSelector.setOnClickListener(this);
        mCarType = findViewById(R.id.layout_car_type);

        //
        mCarTypePickerView = new HashMultiPickerView();
        mHashMapCarTypeArray = new HashMap<>();
        mHashKeyArray = new ArrayList<>();
        initTruckClassInfo();
        mCarTypePickerView.init(this, mHashMapCarTypeArray, mHashKeyArray);

        //
        mResourceTypeSelector = findViewById(R.id.layout_resource_type_selector);
        mResourceTypeSelector.setOnClickListener(this);
        mResourceType = findViewById(R.id.layout_resource_type);
        //
        mResourceTypePickerView = new MultiPickerView();
        mResourceTypeArray = new ArrayList<>();
        initResourceTypeInfo();
        mResourceTypePickerView.init(this, mResourceTypeArray);

        //
        mSelectPicture = (HashMap<String, String>) getIntent().getSerializableExtra("info");

        mInputView = findViewById(R.id.input_view);
        // 创建弹出键盘
        mPopupKeyboard = new PopupKeyboard(this);
        // 弹出键盘内部包含一个KeyboardView，在此绑定输入两者关联。
        mPopupKeyboard.attach(mInputView, this);
        mPopupKeyboard.getController().addOnInputChangedListener(new OnInputChangedListener() {
            @Override
            public void onChanged(String s, boolean b) {

            }

            @Override
            public void onCompleted(String s, boolean b) {
                mPopupKeyboard.dismiss(EnterPlatformPersonalStepTwoActivity.this);
            }
        });
    }

    private void initTruckClassInfo(){
        mHashMapCarTypeArray.clear();
        mHashKeyArray.clear();
        if(AttrInfoController.Instance().getTruckTypeArray() != null &&
                AttrInfoController.Instance().getTruckTypeArray().size() > 0){
            for(int index = 0; index < AttrInfoController.Instance().getTruckTypeArray().size(); index++){
                TruckTypeInfo truckTypeInfo = AttrInfoController.Instance().getTruckTypeArray().get(index);
                List<TruckClassInfo> list = truckTypeInfo.getList();
                ArrayList<MultiItemBean> arrayList = new ArrayList<>();
                for(int index2 = 0; index2 < list.size(); index2++) {
                    MultiItemBean bean = new MultiItemBean();
                    bean.setName(list.get(index2).getClassname());
                    bean.setId(list.get(index2).getClassid());
                    bean.setSelected("0");
                    arrayList.add(bean);
                }
                mHashMapCarTypeArray.put(truckTypeInfo.getType(), arrayList);
                mHashKeyArray.add(truckTypeInfo.getType());
            }
        }
    }

    private void addCarTypeItem(String selectKey, List<Integer> select) {
        if(select == null){
            return;
        }

        mCarType.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(getBaseContext());
        for(int index = 0; index < select.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);

            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(getBaseContext(), 0),
                    0,
                    12,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mHashMapCarTypeArray.get(selectKey).get(select.get(index)).getName());
            itemLayout.setBackgroundResource(R.drawable.rounded_button);
            mCarType.addView(itemLayout);
        }
    }

    private void showCarTypeSelector(){
        MultiPickerConfig pickerConfig = new MultiPickerConfig.Builder()
                .title("选择类型")
                .setCustomItemLayout(R.layout.item_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_city_name_tv)
                .couldSelectNum(1)
                .build();
        pickerConfig.setTitleBackgroundColorStr("#FFD401");

        mCarTypePickerView.setConfig(pickerConfig);
        mCarTypePickerView.setOnMultiItemClickListener(new OnHashMultiPickerItemClickListener() {
            public void onSelected(String selectKey, List<Integer> select) {
                Log.d(TAG, "selectKey: " + selectKey);
                Log.d(TAG, "select: " + select.toString());
                mSelectTruckCid = select;
                mSelectorTruck_cidKey = selectKey;
                addCarTypeItem(selectKey, select);
            }

            @Override
            public void onCancel() {
                /**/
            }
        });

        mCarTypePickerView.showHashMultiPicker();
    }

    private void initResourceTypeInfo(){
        mResourceTypeArray.clear();
        List<ResourceTypeInfo3> resourceTypeArray = AttrInfoController.Instance().getResourceTypeArray3();
        if(resourceTypeArray != null && resourceTypeArray.size() > 0){
            for(int index = 0; index < resourceTypeArray.size(); index++){
                MultiItemBean bean = new MultiItemBean();
                bean.setName(resourceTypeArray.get(index).getClassname());
                bean.setId(resourceTypeArray.get(index).getClassid());
                bean.setSelected("0");
                mResourceTypeArray.add(bean);
            }
        }
        Log.d(TAG, "mResourceTypeArray: " + mResourceTypeArray.toString());
    }

    private void addResourceTypeItem(List<Integer> select){
        if(select == null){
            return;
        }

        mResourceType.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(getBaseContext());
        for(int index = 0; index < select.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);

            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(getBaseContext(), 0),
                    0,
                    12,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mResourceTypeArray.get(select.get(index)).getName());
            itemLayout.setBackgroundResource(R.drawable.rounded_button);
            mResourceType.addView(itemLayout);
        }
    }

    private void showResourceTypeSelector(){
        MultiPickerConfig pickerConfig = new MultiPickerConfig.Builder()
                .title("选择类型")
                .build();
        pickerConfig.setTitleBackgroundColorStr("#FFD401");

        mResourceTypePickerView.setConfig(pickerConfig);
        mResourceTypePickerView.setOnMultiItemClickListener(new OnMultiPickerItemClickListener() {
            @Override
            public void onSelected(List<Integer> select) {
                super.onSelected(select);
                mSelectResource = select;
                addResourceTypeItem(select);
            }

            @Override
            public void onCancel() {
                super.onCancel();
            }
        });

        mResourceTypePickerView.showMultiPicker();
    }

    private boolean checkInputSituation(){
        if(mInputView.getNumber() == null || mInputView.getNumber().equals("") ||
                mHeft.getText().toString()  == null || mHeft.getText().toString().equals("") ||
                mSelectorTruck_cidKey == null || mSelectorTruck_cidKey.equals("") ||
                mSelectTruckCid == null || mSelectTruckCid.size() <= 0 ||
                mSelectResource == null || mSelectResource.size() <= 0 ||
                mContactInfo.getText().toString() == null || mContactInfo.getText().toString().equals("") ||
                mTelephoneInfo.getText().toString() == null || mTelephoneInfo.getText().toString().equals("")
        ){
            return false;
        }

        return true;
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_action_commit){
            if(checkInputSituation()) {
                executeCommitAction();
            }
            else{
                ToastUtils.showLongToast(this, "请填写完整的入驻信息");
            }
        }
        else if(v.getId() == R.id.ic_add_item){
            if(mContactExtra.getVisibility() == View.VISIBLE){
                ToastUtils.showLongToast(this, "最多添加两个联系人！");
            }
            else{
                mContactExtra.setVisibility(View.VISIBLE);
            }
        }
        else if(v.getId() == R.id.layout_car_type_select){
            showCarTypeSelector();
        }
        else if(v.getId() == R.id.layout_resource_type_selector){
            showResourceTypeSelector();
        }
        else{
            /**/
        }
    }

    private void executeCommitAction(){
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("token", AuthController.Instance().getToken());

        JSONObject json = new JSONObject();
        try {
            json.put("classid", mHashMapCarTypeArray.get(mSelectorTruck_cidKey).get(mSelectTruckCid.get(0)).getId());
            json.put("truckno", mInputView.getNumber());
            json.put("main_pic", "reserved");
            json.put("area_id", "reserved");
            json.put("cname", "reserved");


            JSONArray array = new JSONArray();
            JSONObject object = new JSONObject();

            object.put("contact", mContactInfo.getText().toString());
            object.put("mobilephone", mTelephoneInfo.getText().toString());
            array.put(0,object);
            if (mContactInfoExtra.getText().toString() != null &&
                    !mContactInfoExtra.getText().toString().equals("") &&
                    mTelephoneInfoExtra.getText().toString() != null &&
                    !mTelephoneInfoExtra.getText().toString().equals("")
            ) {
                JSONObject object_extra = new JSONObject();

                object_extra.put("contact", mContactInfoExtra.getText().toString());
                object_extra.put("mobilephone", mTelephoneInfoExtra.getText().toString());

                array.put(1,object_extra);
            }

            json.put("contact_data", array);
            json.put("road_transport", mSelectPicture.get("transportLicense"));
            json.put("supercargo", mSelectPicture.get("employeeLicense"));
            json.put("qualification", mSelectPicture.get("qualificationCertificate"));
            json.put("driving_permit", mSelectPicture.get("driverLicense"));
            String core_attr = "";
            for(int index = 0; index < mSelectResource.size(); index++){
                core_attr += mResourceTypeArray.get(mSelectResource.get(index)).getName() + ",";
            }
            if(core_attr.length() > 0){
                core_attr = core_attr.substring(0, core_attr.length() - 1);
            }
            json.put("core_attr", core_attr);
            json.put("length", "3.8");
            json.put("weight", mHeft.getText().toString());
            Log.d(TAG, "param: " + json.toString());

            sendHttpJsonRequest(
                    RemoteAPI.REQUEST_V1_USER_REGISTER_TRUCK,
                    header,
                    json,
                    RemoteAPICmd.REQUEST_V1_USER_REGISTER_TRUCK);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_V1_USER_REGISTER_TRUCK){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    //!TODO:入驻成功之后，通知入驻模块去更新后台的入驻信息
                    UserInfoController.Instance().updateUserInfo();
                    EnterPlatformInfoController.Instance().updateEnterStatus();
                    Intent intent = new Intent(this, EnterPlatformPersonalSuccessActivity.class);
                    intent.putExtra("tid", res.getJSONObject("data").getString("tid"));
                    startActivity(intent);
                }
                else{
                    ToastUtils.showLongToast(this, res.getString("message"));
                }
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_V1_USER_REGISTER_TRUCK){
            ToastUtils.showLongToast(this, "连接超时，入驻失败！");
        }
        else{

        }
    }
}